import os
import numpy as np
import cv2
from PySide6.QtGui import  QImage
from core.log import logger
from core.mhmapconfig import mhmapping

def decode_loc(loc):
    s = loc.split()
    if len(s) != 3:
        logger.info(f"loc length must be 3, current is {len(s)}. {loc}")
        return None, False
    # logger.info(s)
    
    if s[0] in mhmapping:
        v = mhmapping[s[0]]
        try:
            x = int(s[1])
            y = int(s[2])
            if x > v[1]:
                x = 1
            else:
                x = 1.0 * x / v[1]
            if y > v[2]:
                y = 1
            else:
                y = 1.0 * y / v[2]
            return (s, x, y), True
        except ValueError:
            logger.error(f"x: {s[1]}, y: {s[2]} convert to int failed")
            return None, False
    else:
        logger.error(f"{s[0]} not in map")
        return None, False

def image_load_check(image, map_img_path):
    # 检查是否成功加载图像
    if image is None:
        # 打印错误消息
        logger.error(f"Failed to load image.")

        # 打印图像路径，确保路径正确
        logger.error("Image path:", map_img_path)

        # 检查路径中是否包含非ASCII字符，可能导致加载失败
        if any(ord(char) > 128 for char in map_img_path):
            logger.error("Image path contains non-ASCII characters.")

        # 检查图像路径是否存在
        if not os.path.isfile(map_img_path):
            logger.error("Image path does not exist.")

        # 检查图像是否为空文件
        if os.path.exists(map_img_path) and os.path.getsize(map_img_path) == 0:
            logger.error("Image file is empty.")

        # 检查图像是否处于正确的格式
        supported_formats = [".jpg", ".jpeg", ".png", ".bmp"]
        file_format = os.path.splitext(map_img_path)[1].lower()
        if file_format not in supported_formats:
            logger.error("Unsupported image format. Supported formats:", supported_formats)

        # 检查是否缺少依赖项或安装了错误的OpenCV版本
        logger.error("OpenCV version:", cv2.__version__)

        # 检查是否存在文件读取权限问题
        if not os.access(map_img_path, os.R_OK):
            logger.error("No read permission for the image file.")

        # 打印完整的异常信息，以便进一步分析
        try:
            image = cv2.imread(map_img_path)
        except Exception as e:
            logger.error("Error message:", e)
    else:
        logger.info(f"Image {map_img_path} loaded successfully.")

def draw_map(map_img_path, factor_x, facotr_y, flag_ocr=False) :
    try:
        # 使用 OpenCV 读取图像
        cv_image = cv2.imread(map_img_path)
        
        image_load_check(cv_image, map_img_path)
        
        # 将图像转换为 RGB 格式
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)

        # 将 OpenCV 图像转换为 QImage
        height, width, channel = cv_image.shape
        logger.info(f"cv2 {height} {width} {factor_x} {facotr_y}")
        bytesPerLine = 3 * width
        
        x = int(width * factor_x)
        y = height - int(height * facotr_y)
        
        r = 8
        if x < r:
            x = r
        elif x > width - r:
            x = width - r
            
        if y > height - r:
            y = height - r
        elif y < r:
            y = r
        
        if flag_ocr:
            cv2.circle(cv_image, (x, y), r, (255, 255, 0), -1)
        else:
            cv2.circle(cv_image, (x, y), r, (255, 0, 0), -1)
        
        qImage = QImage(cv_image.data, width, height, bytesPerLine, QImage.Format_RGB888)
    
        return qImage, True
    except FileNotFoundError:
        logger.error(f"Error: File not found - {map_img_path}")
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        
    return None, False


def draw_map_prec(map_img_path, loc, factor_x, facotr_y, flag_ocr=False) :
    try:
        
        # 使用 OpenCV 读取图像
        cv_image = cv2.imread(map_img_path)
        image_load_check(cv_image, map_img_path)
        # 将图像转换为 RGB 格式
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)

        # 将 OpenCV 图像转换为 QImage
        height, width, channel = cv_image.shape
        logger.info(f"cv2 {height} {width} {factor_x} {facotr_y}")
        
        c_m = loc[0]
        c_x = int(loc[1])
        c_y = int(loc[2])
        
        logger.info(f"draw_map_prec {c_m} {c_x} {c_y}")
        
        angle = 0  # 椭圆的旋转角度
        startAngle = 0  # 扇形的开始角度
        endAngle = 360  # 扇形的结束角度
        if c_x < 50:
            startAngle = 90
            if c_y < 50:
                endAngle = startAngle + 90
            elif c_y > 150:
                startAngle = 180
                endAngle = startAngle + 90
            else:
                endAngle = startAngle + 180
        elif c_x > 150:
            startAngle = 270
            if c_y < 50:
                startAngle = 0
                endAngle = startAngle + 90
            elif c_y > 150:
                endAngle = startAngle + 90
            else:
                endAngle = startAngle + 180
        else:
            if c_y < 50:
                startAngle = 0
                endAngle = startAngle + 180
            elif c_y > 150:
                startAngle = 180
                endAngle = startAngle + 180
            else:
                startAngle = 0
                endAngle = startAngle + 360
        v = mhmapping[c_m] 
        
        r_x = int(width / v[1] * 50)
        r_y = int(height / v[2] * 50)
        
        x = int(width * factor_x)
        y = height - int(height * facotr_y)
        
        # 创建一个同样大小的透明图层
        overlay = np.zeros((cv_image.shape[0], cv_image.shape[1], 4), dtype='uint8')

        # 扇形的参数
        center = (x, y)  # 中心点
        axes = (r_x, r_y)  # 主轴和次轴的长度
       
        color = (0, 255, 0, 127)  # 半透明绿色，注意这里是 RGBA

        # 在透明图层上绘制扇形
        cv2.ellipse(overlay, center, axes, angle, startAngle, endAngle, color, -1)

        # 将透明图层合并到原图上
        alpha_overlay = overlay[:, :, 3] / 255.0
        alpha_image = 1.0 - alpha_overlay

        for c in range(0, 3):
            cv_image[:, :, c] = (alpha_overlay * overlay[:, :, c] +
                                alpha_image * cv_image[:, :, c])
            
        # 将 OpenCV 图像转换为 QImage
        height, width, channel = cv_image.shape
        logger.info(f"cv2 {height} {width} {factor_x} {facotr_y}")
        bytesPerLine = 3 * width
        
        x = int(width * factor_x)
        y = height - int(height * facotr_y)
        
        r = 8
        if x < r:
            x = r
        elif x > width - r:
            x = width - r
            
        if y > height - r:
            y = height - r
        elif y < r:
            y = r
        
        if flag_ocr:
            cv2.circle(cv_image, (x, y), r, (255, 255, 0), -1)
        else:
            cv2.circle(cv_image, (x, y), r, (255, 0, 0), -1)
        
        qImage = QImage(cv_image.data, width, height, bytesPerLine, QImage.Format_RGB888)
    
        return qImage, True
    except FileNotFoundError:
        logger.error(f"Error: File not found - {map_img_path}")
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        
    return None, False
        
        